const { Sequelize, Model, Op } = require("sequelize");
const { db } = require("../core/db");
const { Art } = require("./art");

class Like extends Model {
  static async onLike(art_id, type, uid) {
    const favor = await Like.findOne({
      where: {
        art_id,
        type,
        uid,
      },
    });
    if (favor) {
      throw new global.errs.LikeError();
    }
    try {
      return await db.transaction(async (t) => {
        const like = await Like.findOne({
          where: { art_id, uid, type },
        });
        if (like) {
          like.deleted_at = null;
          await like.save();
        } else {
          await Like.create({ art_id, type, uid }, { transaction: t });
        }
        const art = await Art.getData(art_id, type, false);
        await art.increment("fav_nums", { by: 1, transaction: t });
      });
    } catch (error) {
      throw new Error(error);
    }
  }

  static async disLike(art_id, type, uid) {
    const favor = await Like.findOne({
      where: {
        art_id,
        type,
        uid,
      },
    });
    if (!favor) {
      throw new global.errs.DislikeError();
    }
    try {
      return await db.transaction(async (t) => {
        await favor.destroy({ force: true, transaction: t });
        const art = await Art.getData(art_id, type, false);
        await art.decrement("fav_nums", { by: 1, transaction: t });
      });
    } catch (error) {
      throw new Error(error);
    }
  }

  static async userLike(art_id, type, uid) {
    const like = await Like.findOne({ where: { art_id, type, uid } });
    return like ? true : false;
  }

  static async getMyLikeClassic(uid) {
    const arts = await Like.findAll({
      where: {
        uid,
        type: {
          [Op.not]: 400,
        },
      },
    });
    if (!arts) {
      throw new global.errs.NotFound();
    }

    const res = await Art.getList(arts);
    return res;
  }

  static async getLikeList(artIds,type) {
    const likes = await Like.findAll({
      where: {
        art_id: {
          [Op.in]: artIds,
        },
        type
      },
      group: ['art_id'],
      attributes: ['art_id', [Sequelize.fn('COUNT', '*'), 'count']],
    });
    return likes;
  }


  static async getBookLike(uid,bookId){
    const likeStatus = await Like.findOne({
      where:{
        uid,
        art_id:bookId,
        type:400
      }
    })
    const count = await Like.count({
      where:{
        art_id:bookId,
        type:400
      }
    })
    return {
      likeStatus:likeStatus?1:0,
      count
    }
  }
}

Like.init(
  {
    art_id: Sequelize.INTEGER,
    type: Sequelize.INTEGER,
    uid: Sequelize.INTEGER,
  },
  { sequelize: db, tableName: "favor" }
);

module.exports = {
  Like,
};
